/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.dao;

import java.util.List;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author carlos
 */
@Named
@Stateless
@PermitAll
public class GenericDAO<T> {

    @PersistenceContext
    private EntityManager em;
    private Class<T> persistenceClass;

    public GenericDAO() {
    }

    public GenericDAO(Class<T> persistenceClass) {
        this.persistenceClass = persistenceClass;
    }

    public void insert(T obj) {
        em.persist(obj);
    }

    public T update(T obj) {
        em.merge(obj);
        return obj;
    }

    public boolean delete(T obj) {
        try {
            em.remove(obj);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public T findById(Object id) {
        return em.find(persistenceClass, id);
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public List<T> getAll() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<T> cq = cb.createQuery(persistenceClass);
        Root<T> obj = cq.from(persistenceClass);
        cq.select(obj);
        return em.createQuery(cq).getResultList();
    }
}
